﻿/*
 * Created by SharpDevelop.
 * User: Administrator
 * Date: 2/15/2011
 * Time: 9:02 PM
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using Microsoft.Synchronization;
using System.Collections;
using System.Collections.Generic;
using HtmlAgilityPack;
using System.Web.Script.Serialization;

namespace TomatoSynchronizer
{
	/// <summary>
	/// Description of TomatoSyncProvider.
	/// </summary>
	public class TomatoSyncProvider : KnowledgeSyncProvider
	{
		private HtmlWeb _client;
		private string _url;
		private string _name;
		private string _user;
		
		public string User {
			get { return _user; }
			set { _user = value; }
		}
		private string _pass;
		
		public string Pass {
			get { return _pass; }
			set { _pass = value; }
		}
		
		public string Name {
			get { return _name; }
			set { _name = value; }
		}
		
		public string Url {
			get { return _url; }
			set { _url = value; }
		}
		
		public TomatoSyncProvider(string name,string url,string user,string pass)
		{			
			this._name = name;
			this._url = url;
			this._user = user;
			this._pass = pass;
			_client = new HtmlWeb();
		}
		
		public override void BeginSession(SyncProviderPosition position, SyncSessionContext syncSessionContext)
		{		
			if(!Login(_client))
			{
				throw new Exception("Could not begin a session : bad username or password");
			}
		}
		
		public override void EndSession(SyncSessionContext syncSessionContext)
		{
			Logout(_client);
		}
		
		public override ChangeBatch GetChangeBatch(uint batchSize, SyncKnowledge destinationKnowledge, out object changeDataRetriever)
		{
			throw new NotImplementedException();
		}
		
		public override FullEnumerationChangeBatch GetFullEnumerationChangeBatch(uint batchSize, SyncId lowerEnumerationBound, SyncKnowledge knowledgeForDataRetrieval, out object changeDataRetriever)
		{
			throw new NotImplementedException();
		}
		
		public override void GetSyncBatchParameters(out uint batchSize, out SyncKnowledge knowledge)
		{
			throw new NotImplementedException();
		}
		
		public override void ProcessChangeBatch(ConflictResolutionPolicy resolutionPolicy, ChangeBatch sourceChanges, object changeDataRetriever, SyncCallbacks syncCallbacks, SyncSessionStatistics sessionStatistics)
		{
			throw new NotImplementedException();
		}
		
		public override void ProcessFullEnumerationChangeBatch(ConflictResolutionPolicy resolutionPolicy, FullEnumerationChangeBatch sourceChanges, object changeDataRetriever, SyncCallbacks syncCallbacks, SyncSessionStatistics sessionStatistics)
		{
			throw new NotImplementedException();
		}		
		
		private SyncIdFormatGroup _idFormats;
		public override SyncIdFormatGroup IdFormats { 
			get { return _idFormats; }
		}
		
		private void Logout(HtmlWeb client)
		{
			bool succes = false;
			string reponse;	
			if(!string.IsNullOrEmpty(_user) && !string.IsNullOrEmpty(_pass))
			{				
				HtmlDocument doc = client.Load(_url + "/admin/json.php?action=logoff&module=login");
				HtmlNode node = doc.DocumentNode.SelectSingleNode("/");				
				reponse = node.InnerText;
				JavaScriptSerializer serialiser = new JavaScriptSerializer();//			
				IDictionary json = serialiser.Deserialize<IDictionary>(reponse);
				foreach(string key in json.Keys)
				{
					if(key == "success")
					{
						bool.TryParse(json[key].ToString(),out succes);
					}
				}
			}					
			
//			return succes;
		}
		
		private bool Login(HtmlWeb client)
		{
			bool succes = false;
			string reponse;	
			if(!string.IsNullOrEmpty(_user) && !string.IsNullOrEmpty(_pass))
			{				
				HtmlDocument doc = client.Load(_url + "/admin/json.php?action=login&language=en_US&module=login&user_name=" + _user + "&user_password=" + _pass);
				HtmlNode node = doc.DocumentNode.SelectSingleNode("/");				
				reponse = node.InnerText;
				JavaScriptSerializer serialiser = new JavaScriptSerializer();//			
				IDictionary json = serialiser.Deserialize<IDictionary>(reponse);
				foreach(string key in json.Keys)
				{
					if(key == "success")
					{
						bool.TryParse(json[key].ToString(),out succes);
					}
				}
			}					
			
			return succes;
		}
	}
}